import { Plugin } from 'vite'
import fs from 'node:fs'
import path from 'node:path'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

interface Options {
    dts: string | boolean // 输出的.d.ts文件路径
    prefix: string
}

// 插件的配置
export default function IconTypesPlugin(options: Options): Plugin {
    const { dts, prefix } = options
    return {
        name: 'vite-plugin-elementplusicons-types',
        enforce: 'pre', // 插件执行顺序
        configResolved() {
            if (!dts) return
            let defaultDts = './src/types/el-icon-name.d.ts'
            if (dts !== true) {
                defaultDts = dts
            }
            // 输出文件路径
            const outputPath = path.normalize(path.resolve(__dirname, '..', defaultDts))
            // 生成dts
            const dtsFile = generateDTS(ElementPlusIconsVue, prefix, 'ElIconNameType')
            // 保存
            writeFile(dtsFile, outputPath)
        },
    }
}

function generateDTS(icons: any, prefix: string, typeName: string): string {
    let type: string = ''
    let iconNameArr: string[] = []
    for (const key1 in icons) {
        if (Object.prototype.hasOwnProperty.call(icons, key1)) {
            type = type + '|' + `'${prefix}-${icons[key1].name}'`
            iconNameArr.push(`'${prefix}-${icons[key1].name}'`)
        }
    }
    const icontype = `export type ${typeName} = \n${type}\n`
    const iconName = `export const elIconNames = [\n${iconNameArr}\n]`
    return icontype + iconName
}
function writeFile(dtsFile: string, outputPath: string) {
    // // 创建输出目录（如果不存在）
    const outputDir = path.dirname(outputPath)
    if (!fs.existsSync(outputDir)) {
        fs.mkdirSync(outputDir, { recursive: true })
    }
    // 写入文件
    fs.writeFileSync(outputPath, dtsFile)
}
